#include <fstream>
#include <iostream>
#include "Scene.h"
#include "GameIO.h"
#include "Pig.h"
#include "FlyBird.h"

using namespace std;

Scene :: Scene()
{
	loadBgImg();
	loadMapImg();
	loadMapFile("maps\\1.map");
	camera.x = 0; camera.y = 0;
	camera.w = SCREEN_WIDTH; camera.h = SCREEN_WIDTH;

	pig = new Pig();
	setBackground();

	flyBird = new FlyBird();
	flyBird->loadBirdImg();
	delete flyBird;
}

void Scene :: moveScene(int v)
{
	camera.x += v;
}

intXY Scene :: getMap()
{
	return map;
}

SDL_Rect* Scene :: getCamera()
{
	return &camera;
}

Background** Scene :: getBackground()
{
	return background;
}

SDL_Surface** Scene :: getMapImg()
{
	return mapImg;
}

void Scene :: loadBgImg()
{
	bgImg[0] = GameIO :: loadImg("pics\\bg0.bmp");
}

void Scene :: loadMapImg()
{
	string imgPath;

	for(int i = 0; i < BIRDTYPE_NUM; i++)
	{
		imgPath = "pics\\bird" + GameIO :: conToStr(i) + ".bmp";
		mapImg[i] = GameIO :: loadImg(imgPath);
		SDL_SetColorKey(mapImg[i], SDL_RLEACCEL|SDL_SRCCOLORKEY, SDL_MapRGB(mapImg[i]->format, 250, 250, 250));
	}

	mapImg[6] = GameIO :: loadImg("pics\\egg.bmp");
	SDL_SetColorKey(mapImg[6], SDL_RLEACCEL|SDL_SRCCOLORKEY, SDL_MapRGB(mapImg[6]->format, 250, 250, 250));

	mapImg[7] = GameIO :: loadImg("pics\\grass1.bmp");
	SDL_SetColorKey(mapImg[7], SDL_RLEACCEL|SDL_SRCCOLORKEY, SDL_MapRGB(mapImg[7]->format, 250, 250, 250));

	mapImg[8] = GameIO :: loadImg("pics\\helmet.bmp");
	SDL_SetColorKey(mapImg[8], SDL_RLEACCEL|SDL_SRCCOLORKEY, SDL_MapRGB(mapImg[8]->format, 250, 250, 250));

	mapImg[9] = GameIO :: loadImg("pics\\spine.bmp");
	SDL_SetColorKey(mapImg[9], SDL_RLEACCEL|SDL_SRCCOLORKEY, SDL_MapRGB(mapImg[9]->format, 250, 250, 250));
}

void Scene :: loadMapFile(string filePath)
{
	ifstream infile(filePath.data(), ios::in);

	if(!infile)
	{
		cerr << "[Error]: Can not open " << filePath << endl;
		exit(1);
	}

	for(int i = 0; i < LEVEL_HEIGHT / SIZEY; i++)
	{
		for(int j = 0; j < LEVEL_WIDTH / SIZEX; j++)
		{
			infile >> map[i][j];
		}
	}
}

void Scene :: setBackground()
{
	int x = 0;
	int y = 0;
	
	for(int i = 0; i < BG_NUM; i++)
	{
		background[i] = new Background(x, y, bgImg[0]);
		x += bgImg[0]->w;
	}
}